package com.homework.demo6_11.dao.impl;


import com.homework.demo6_11.dao.StudentDAO;
import com.homework.demo6_11.model.Student;

/**
 * StudentDAO接口的实现类
 */
public class StudentDAOImpl implements StudentDAO {
    //定义一个保存学生信息的数组(容器)
    private Student[] students;
    int count;

    //可以使用构造器对这个数组进行初始化
    public StudentDAOImpl() {
        students = new Student[10];//初始化数组容器
    }

    @Override
    public void addStudent(Student stu) {
        if (stu != null) {
            if (count < 6) {
                //如果条件成立，就要将这个学生对象student保存到数组中
                students[count] = stu;
                count++;
                System.out.println("添加成功...");
            } else {
                System.out.println("添加失败...");
            }
        }
    }

    @Override
    public Student queryById(String id) {
        Student stu = null;
        //对数组进行遍历
        for (int i = 0; i < count; i++) {
            //数组中获取元素(通过下标)
            if (students[i] != null) {
                //判断数组中某一个对象的id是否与输入参数id相同
                if (students[i].getId().equals(id)) {
                    stu = students[i];
                }
            }
        }
        return stu;
    }

    @Override
    public Student[] findAll() {
        Student[] student1 = new Student[2];
        for (int i = 0; i < students.length; i++) {
            if (students[i] != null) {
                student1[i] = students[i];
            }
        }
        return student1;
    }

        public static void main(String[] args) {
            StudentDAO dao = new StudentDAOImpl();

            Student student = new Student();
            student.setId("1000");
            student.setName("tom");
            student.setAge(30);
            student.setSchool("foreknow");

            Student student2 = new Student();
            student2.setId("1002");
            student2.setName("tom2");
            student2.setAge(22);
            student2.setSchool("foreknow2");

            //添加学生的信息
            dao.addStudent(student);
            dao.addStudent(student2);
            //根据id获取学生的信息
            //Student stu = dao.queryById("1002");
           // System.out.println(stu.getId() + "--" + stu.getName() + "--" + stu.getSchool());
            Student[] stu=dao.findAll();
            for(int i = 0; i<stu.length; i++) {
                if (stu!=null) {
                    Student student1 = stu[i];
                    System.out.println(student1.getId() + " " + student1.getName() + " " + student1.getAge() + " " + student1.getSchool());
                }
            }
        }
    }
